package com.streamhub.client;

import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONString;
import com.google.gwt.user.client.ui.FlexTable;

public class Stock implements StreamHubGWTUpdateListener {
	private final String symbol;
	private final String company;
	private final double initialPrice;
	private int flexTableRow;
	private FlexTable flexTable;

	public Stock(String symbol) {
		this.symbol = symbol;
		this.company = "-";
		this.initialPrice = 0.0;
	}
	
	public void onUpdate(String topic, JSONObject update) {
		if (symbol.equals(topic)) {
			String lastPrice = ((JSONString)update.get("LastPrice")).stringValue();
			String companyName = ((JSONString)update.get("Company")).stringValue();
			String percentChange = ((JSONString)update.get("PercentChange")).stringValue();
			String change = ((JSONString)update.get("Change")).stringValue();
			Double changeDouble = Double.valueOf(change);
			flexTable.setText(flexTableRow, 1, companyName);
			flexTable.setText(flexTableRow, 2, lastPrice);
			flexTable.setText(flexTableRow, 3, change + " (" + percentChange + ")");
			format(changeDouble);
		}
	}
	
	public void addToFlexTable(FlexTable flexTable) {
		this.flexTable = flexTable;
		flexTableRow = flexTable.getRowCount();
		flexTable.setText(flexTableRow, 0, symbol);
		flexTable.setText(flexTableRow, 1, company);
		flexTable.setText(flexTableRow, 2, "" + initialPrice);
		flexTable.setText(flexTableRow, 3, "0.0 (0.00%)");	
		flexTable.getCellFormatter().addStyleName(flexTableRow, 2, "stockTableNumeric");
		flexTable.getCellFormatter().addStyleName(flexTableRow, 3, "stockTableNumeric");
	}

	private void format(Double changeDouble) {
		if (changeDouble > 0.0) {
			flexTable.getCellFormatter().setStyleName(flexTableRow, 3, "green");
		} else if (changeDouble == 0.0) {
			flexTable.getCellFormatter().setStyleName(flexTableRow, 3, "black");
		} else {
			flexTable.getCellFormatter().setStyleName(flexTableRow, 3, "red");
		}
	}
}
